/**
 * The is the main entry point in the application. It will parse the command line options, process the given torrents, if present; and start the GUI if requested.
 */
package org.jget.controller;

import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.jget.controller.utils.FileUtils;
import org.jget.view.Mainframe;

/**
 * @author ties
 *
 */
public class Main {
	public enum DownloadType {
		TorrentFile, Url, Unrecognized
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		boolean startUI = handleParameters(args);
		if (startUI) {
			new Mainframe("JGet").setVisible(true);
		}
	}

	private static Options initializeOptions() {
		Options options = new Options();
		options.addOption("q", "quit", false, "quit after adding files (don't start the UI)");
		options.addOption("h", "help", false, "print this message");
		return options;
	}

	private static boolean handleParameters(String[] args) {
		CommandLineParser parser = new PosixParser();
		Options opts = initializeOptions();
		CommandLine line = null;
		try {
			line = parser.parse(opts, args);
		}
		catch(ParseException exp) {
			System.out.println("ERROR: " + exp.getMessage());
			return true;
		}
		if (line.hasOption("help")) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp( "JGet [OPTION] [torrentfile] [URL]", opts );
			return false;
		}
		if (!line.getArgList().isEmpty()) {
			addDownloads(line.getArgs());
			return !line.hasOption("quit");
		}
		return true;
	}

	private static void addDownloads(String[] downloads) {
		QNapController controller = new QNapController();
		if(!controller.checkServer()) {
			System.out.println("ERROR: could not connect to the NAS, configure the app using the GUI");
			return;
		}
		for (String download: downloads) {
			switch (determineDownloadType(download)) {
				case TorrentFile:
					File f = new File(download);
					if (f.exists()) {
						controller.addTorrent(f);
					}
					break;
				case Url:
					System.out.println("WARNING: support for adding non-Torrent files has been\n" +
										"\t\tremoved (eg. URLs starting with 'http://' or 'ftp://'),\n" + 
										"\t\tuse the GUI instead.");
					//mainFrame.showAddFtpDialog(args[i]);
					break;
				case Unrecognized:
					System.out.println("ERROR: unrecognized download type");
					break;
			}
		}
	}

	private static DownloadType determineDownloadType(String download) {
		if(FileUtils.getExtension(download).equalsIgnoreCase("torrent"))
			return DownloadType.TorrentFile;
		
		if (download.startsWith("http") || download.startsWith("ftp"))
			return DownloadType.Url;
		
		return DownloadType.Unrecognized;
	}
}
